package org.wtfbbq.util;

import java.util.Properties;

/**
 * Config file manager
 * @author Tim Fennis
 */
public final class Config
implements Installable {
	
	/**
	 * The cfg filename
	 */
	private File fullname = null;
	
	/**
	 * the internal properties
	 */
	private Properties properties = null;
	
	/**
	 * autosave
	 */
	private boolean cacheEnabled = true;
	
	/**
	 * 
	 */
	public Config ( String fullname ) {
		this.fullname = new File ( fullname );
	}
	
	/**
	 * Add item to config
	 *
	 */
	public void set ( String key , String value ) {
		properties.setProperty(key,value);
		if ( ! cacheEnabled )
			save();
	}
	
	/**
	 *
	 */
	public String get ( String key ) {
		if ( ! cacheEnabled )
			load();
		return properties.getProperty(key);
	}
	
	/**
	 * Prepare the config utility for use
	 * Creates the config file
	 * @return boolean true on succes and false if the utility is already installed
	 * @throws IOException if the config file couldn't be created
	 */
	public boolean install ( String[] params ) throws IOException { 
		boolean b = true;
		try {
			if ( ! fullname.exists() ) {
				fullname.createNewFile();
			} else {
				b = false;
			}
		} catch ( IOException io ) {
			throw new IOException ( "Error creating config file: " + io.getMessage() );
		}
		
		if ( ! fullname.canRead() ) {
			throw new IOException ( "Can't read from "+ fullname.getName() );
		}
		
		if ( ! fullname.canRead() ) {
			throw new IOException ( "Can't write to file "+ fullname.getName() +" file is readonly" );
		}
		
		return b;
	}
	
	/**
	 *
	 */
	public void load ( ) {
		properties = new Properties ( );
		properties.load( new InputStreamReader ( new FileInputStream ( fullname ) ) );
	}
	
	/**
	 *
	 */
	public void save ( ) {
		properteis.save( new PrintStream( fullname ) , getComments() );
	}
	
	/**
	 *
	 *
	 *
	 */
	public void backup ( String name ) throws IOException {
		String path = get( "cfg_backup_path" );
		File f = new File ( path + '/' + name );
		f.createNewFile();
		p.storeToXML( new PrintStream ( f ) , getComments() , "UTF-16" );
	}
	
	/**
	 *
	 *
	 *
	 */
	private String getComments ( ) {
		return Calendar.getInstance().getTime().toString();
	}
}